/* api */
import { getDoorType, updateDoorType } from '@src/api/PortalApi'
/* entry */
import DoorType, { DoorTypeNav } from '@model/entity/DoorType'
/* hooks */
import { useFetchResult } from '@hooks/useFetch'
import { useBack, useUrlParams } from '@hooks/useWindow'
import { useTenantId } from '@hooks/useRootWindow'
/* model */
import { GetDoorTypeResult, UpdateDoorTypeResult } from '@model/param/out/Portal'
import { GetDoorTypeModel, UpdateDoorTypeModel } from '@model/param/in/Portal'
/* util */
import Platform from '@src/util/platform'
import { isEmpty } from '@src/util/type'
/* vue */
import { computed, ComputedRef, onMounted, reactive, ref, Ref, ToRefs, toRefs, watch } from 'vue'
import Log from '@src/util/log'
import { cloneDeep } from 'lodash'
import { arrayToObject } from '@src/util/array'


type UsePortalConfigReturnType = [
  ComputedRef<DoorType>, 
  Ref<string>,
  Ref<DoorTypeNav[]>, 
  ComputedRef<DoorTypeNav[]>,
  ComputedRef<boolean>,
  (doorTypeNav: DoorTypeNav[]) => void,
  (themeColour: string) => void,
  (doorType: DoorType) => void
]

interface PortalConfigUrlParamsType {
  id: string | number,
  tab: 'nav' | string
}

// const SHOP_KEY = '商城'

function getTabBarList(doorType: DoorType): DoorTypeNav[] {
  // 导航数据
  let doorNavigation: Record<string, DoorTypeNav> = doorType?.setting?.doorNavigation || {}
  
  return (
    Object.keys(doorNavigation)
      .map((doorNavigationKey: string) => {
        return doorNavigation[doorNavigationKey]
      })
      .sort((a, b) => {
        return a.order - b.order
      })
  )
}

function getCheckedColor(doorType: DoorType): string {
  return doorType?.setting?.doorStyle?.themeColour || "#FF7100,#FFFFFF";
}

function isNotDoorTypeDisabled(doorTypeNav: DoorTypeNav) {
  return !doorTypeNav.disabled
}

function isDoorTypeVisible(doorTypeNav: DoorTypeNav) {
  return doorTypeNav.isVisible
}

function buildDoorType(doorType: Ref<DoorType>, tabBarList: Ref<DoorTypeNav[]>): Ref<DoorType> {
  if (!doorType.value?.setting?.doorNavigation) return doorType
  
  try {
    const savedDoorType: Ref<DoorType> = cloneDeep(doorType)
    const doorNavigation: DoorTypeNav[] = cloneDeep(tabBarList.value).map((nav: DoorTypeNav, index: number) => {
      nav.order = index + 1
      return nav
    })
    
    savedDoorType.value.setting.doorNavigation = arrayToObject(doorNavigation, 'value')
    
    return savedDoorType
    
  } catch (error) {
    Log.error(error, buildDoorType.name)
    return doorType
  }
}

export function usePortalConfig(): UsePortalConfigReturnType {
  // 自主门户模板类型
  const doorType: ComputedRef<DoorType> = useFetchPortalSetting()
  
  // 自助门户配色
  let checkedColor: Ref<string> = ref('')
  
  // 工具栏列表
  let tabBarList: Ref<DoorTypeNav[]> = ref([])
  
  watch(doorType, (newValue, oldValue) => {
    setTabBarList(getTabBarList(newValue))
    setCheckedColor(getCheckedColor(newValue))
  })
  
  // 工具导航栏可见的显示列表
  const tabBarVisibleList: ComputedRef<DoorTypeNav[]> = computed(() => {
    return tabBarList.value.filter((doorTypeNav: DoorTypeNav) => doorTypeNav.isVisible)
  })
  
  // 是否选中全部
  const isCheckedAll: ComputedRef<boolean> = computed<boolean>({
    get() {
      if (isEmpty(tabBarList.value)) {
        return false
      }
      
      return tabBarList.value.filter(isNotDoorTypeDisabled).every(isDoorTypeVisible)
    },
    set(value) {
      setTabBarListIsVisible(value)
    }
  })
  
  function setTabBarListIsVisible(value: boolean) {
    tabBarList.value.forEach((doorTypeNav: DoorTypeNav) => {
      // 设置非禁用状态下的
      if (!doorTypeNav.disabled) {
        doorTypeNav.isVisible = value
      }
    })
  }
  
  // 更改工具栏列表
  function setTabBarList(doorTypeNavList: DoorTypeNav[]): void {
    tabBarList.value = doorTypeNavList
  }
  
  function setCheckedColor(themeColour: string): void {
    checkedColor.value = themeColour;
    doorType.value.setting.doorStyle.themeColour = themeColour;
  }
  
  function save() {
    useFetchUpdatePortalSetting(buildDoorType(doorType, tabBarList))
  }
  
  return [doorType, checkedColor, tabBarList, tabBarVisibleList, isCheckedAll, setTabBarList, setCheckedColor, save]
}

export function useFetchPortalSetting(): ComputedRef<DoorType> {
  const params: ComputedRef<GetDoorTypeModel> = useFetchPortalSettingParams()
  
  let [data, callback] = useFetchResult<GetDoorTypeModel, DoorType>(async () => {
    return getDoorType(params.value)
  }, params.value)
  
  callback()
  
  return computed(() => data.value as DoorType)
}

export function useFetchPortalSettingParams(): ComputedRef<GetDoorTypeModel> {
  const urlParams: ComputedRef<PortalConfigUrlParamsType> = useUrlParams<PortalConfigUrlParamsType>()
  const tenantId: ComputedRef<string> = useTenantId()
  
  return computed(() => ({ tenantId: tenantId.value, id: urlParams.value.id }))
}

export function useFetchUpdatePortalSetting(doorType: Ref<DoorType>): ComputedRef<null> {
  const params: ComputedRef<UpdateDoorTypeModel> = useFetchUpdatePortalSettingParams(doorType)
  
  const [data, callback] = useFetchResult<UpdateDoorTypeModel, null>(async () => {
    return updateDoorType(params.value)
  }, params.value)
  
  // FIXME: 暂时先这么蠢
  callback((result: UpdateDoorTypeResult) => {
    const isSuccess = Boolean(result?.success)
    if (isSuccess) {
      // Platform.alert('保存配置成功！')
      Platform.notification({
        title: '成功',
        type: 'success',
        message: '保存配置成功！',
      })
      useBack()()
    } else {
      Platform.notification({
        title: '发布失败',
        type: 'error',
        message: result.message,
      })
    }
  })
  
  return computed(() => data.value)
}

export function useFetchUpdatePortalSettingParams(doorType: Ref<DoorType>): ComputedRef<UpdateDoorTypeModel> {  
  return computed(() => doorType.value)
}
